// pages/my-bulk-material-detail/my-bulk-material-detail.ts
import { getPublishDetail, closePublish, setReadStatus } from '../../../api/publish';
import { goBack, PAGES, goToPage } from '../../../config/pages';
import { formatSpecification } from '../../../utils/util';

Page({
  data: {
    id: '',
    detail: null as any,
    loading: true,
    closing: false,
    // 留言弹窗相关
    showMessageModal: false,
    selectedMessage: null as any,
  },

  onLoad(options: any) {
    const { id } = options;
    if (id) {
      this.setData({ id });
      this.loadDetail();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none',
      });
      setTimeout(() => {
        goBack();
      }, 1500);
    }
  },

  async loadDetail() {
    this.setData({ loading: true });

    try {
      const res = await getPublishDetail(Number(this.data.id));

      if ((res.status === 200 || res.code === 200) && res.data) {
        // 格式化规格信息
        const formattedDetail = {
          ...res.data,
          spec: formatSpecification(res.data.spec || '')
        };
        
        // 格式化参与者时间
        if (formattedDetail.participants && formattedDetail.participants.length > 0) {
          formattedDetail.participants = formattedDetail.participants.map((participant: any) => ({
            ...participant,
            add_time: this.formatTime(participant.add_time),
            // 添加留言状态
            hasMessage: !!(participant.remark_corp || participant.remark_name || participant.remark_phone || participant.remark_content),
            isRead: participant.is_read || false,
            avatar_name: this.getAvatarName(participant.user)
          }));
        }
        
        this.setData({
          detail: formattedDetail,
          loading: false,
        });
      } else {
        wx.showToast({
          title: res.msg || '加载失败',
          icon: 'none',
        });
        this.setData({ loading: false });
      }
    } catch (error: any) {
      console.error('加载详情失败:', error);
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.message || '加载失败'),
        icon: 'none',
      });
      this.setData({ loading: false });
    }
  },

  // 获取头像名称
  getAvatarName(user: any) {
    if (!user) return '匿';
    
    // 优先使用real_name，其次nickname
    const name = user.real_name || user.nickname;
    if (!name || name === 'null' || name.length === 0) {
      return '匿';
    }
    
    return name.charAt(0);
  },

  // 格式化时间
  formatTime(timeStr: string) {
    if (!timeStr) return '';
    
    const date = new Date(timeStr);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    
    // 计算时间差
    const minutes = Math.floor(diff / (1000 * 60));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (minutes < 1) {
      return '刚刚';
    } else if (minutes < 60) {
      return `${minutes}分钟前`;
    } else if (hours < 24) {
      return `${hours}小时前`;
    } else if (days < 7) {
      return `${days}天前`;
    } else {
      // 超过7天显示具体日期
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hour = String(date.getHours()).padStart(2, '0');
      const minute = String(date.getMinutes()).padStart(2, '0');
      
      if (year === now.getFullYear()) {
        return `${month}-${day} ${hour}:${minute}`;
      } else {
        return `${year}-${month}-${day} ${hour}:${minute}`;
      }
    }
  },

  // 查看技术参数
  viewTechParams() {
    const { detail } = this.data;
    if (!detail) {
      wx.showToast({ title: '暂无技术参数', icon: 'none' });
      return;
    }

    const files = ([] as any[])
      .concat(detail.tech_params_files || [])
      .concat(detail.tech_params_atts || []);
    if (!files || files.length === 0) {
      wx.showToast({ title: '暂无技术参数', icon: 'none' });
      return;
    }

    const comp = this.selectComponent('#mediaViewer');
    if (comp && typeof (comp as any).open === 'function') {
      (comp as any).open(files);
    } else {
      wx.showToast({ title: '组件不可用', icon: 'none' });
    }
  },

  // 跳转到企业详情页面
  goToCompanyProfile(e: any) {
    const enterpriseId = e.currentTarget.dataset.enterpriseId;
    if (enterpriseId) {
      goToPage('/pages/enterprise/company-profile/company-profile', { enterpriseId });
    } else {
      wx.showToast({
        title: '企业信息不存在',
        icon: 'none'
      });
    }
  },

  // 查看留言
  viewMessage(e: any) {
    const { participant } = e.currentTarget.dataset;
    this.setData({
      showMessageModal: true,
      selectedMessage: participant
    });
  },

  // 关闭留言弹窗
  closeMessageModal() {
    this.setData({
      showMessageModal: false,
      selectedMessage: null
    });
  },

  // 标记为已读
  async markAsRead(e: any) {
    const { participant } = e.currentTarget.dataset;
    
    try {
      const res = await setReadStatus(participant.id, 1);
      
      if (res.status === 200 || res.code === 200) {
        // 更新本地数据
        const participants = this.data.detail.participants.map((p: any) => {
          if (p.id === participant.id) {
            return { ...p, isRead: true };
          }
          return p;
        });
        
        this.setData({
          'detail.participants': participants
        });
        
        wx.showToast({
          title: '已标记为已读',
          icon: 'success',
        });
      } else {
        wx.showToast({
          title: res.msg || '标记失败',
          icon: 'none',
        });
      }
    } catch (error: any) {
      console.error('标记已读失败:', error);
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.msg || '标记失败，请重试'),
        icon: 'none',
      });
    }
  },

  // 编辑散料
  editMaterial() {
    goToPage(PAGES.MY_BULK_MATERIAL_EDIT, { id: this.data.id });
  },

  // 关闭散料
  closeMaterial() {
    wx.showModal({
      title: '关闭散料',
      content: '确定要关闭这个散料吗？关闭后将无法接收新的询价。',
      confirmText: '确定关闭',
      confirmColor: '#d54941',
      success: async (res) => {
        if (res.confirm) {
          this.setData({ closing: true });

          try {
            const result = await closePublish(Number(this.data.id), {});

            if (result.status === 200) {
              wx.showToast({
                title: '关闭成功',
                icon: 'success',
              });
              // 刷新数据
              this.loadDetail();
            } else {
              wx.showToast({
                title: result.msg || '关闭失败',
                icon: 'none',
              });
              this.setData({ closing: false });
            }
          } catch (error: any) {
            console.error('关闭散料失败:', error);
            wx.showToast({
              title: typeof(error) === 'string' ? error : (error?.message || '关闭失败'),
              icon: 'none',
            });
            this.setData({ closing: false });
          }
        }
      },
    });
  },
});

